package com.vanysoft.business.sys.service.impl;

import com.vanysoft.business.sys.dao.RoleMapper;
import com.vanysoft.business.sys.entity.Role;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.business.sys.service.RoleService;
import com.vanysoft.business.sys.service.UserInfoService;
import com.vanysoft.framework.config.database.BaseServiceImpl;
import com.vanysoft.framework.config.database.PageInfo;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色服务类实现
 *
 * @author qi_ma
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private UserInfoService userInfoService;

    @Override
    public List<Role> selectByUserId(String userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public PageInfo<Role> selectAll(PageInfo<Role> page) {
        Map<String, Object> condition = page.getCondition();
        page.setRecords(baseMapper.selectAll(page, page.getCondition()));
        condition.put("isEnable", "1");
        Integer notForbidden = baseMapper.selectCount(condition);
        condition.put("isEnable", "0");
        Integer forbidden = baseMapper.selectCount(condition);
        Map<String, Object> other = new HashMap<>();
        other.put("forbidden", forbidden);
        other.put("notForbidden", notForbidden);
        page.setOther(other);
        return page;
    }

    @Override
    public List<Role> selectAll(Map<String, Object> condition) {
        return baseMapper.selectAll(condition);
    }

    @Override
    public boolean deleteByRoleIdAndUserIds(String roleId, String[] userIds) {
        return retBool(baseMapper.deleteByRoleIdAndUserIds(roleId, userIds));
    }

    @Override
    public boolean deleteByIds(String[] ids) {
        List<UserInfo> userInfos = userInfoService.selectByRoleIds(ids);
        if (userInfos.size() > 0) {
            throw new VanySoftBaseException(MessageCodeConstant.RTN_CODE_UNKNOW_ERROR, "请检查该角色下面是否有用户存在");
        }
        return retBool(baseMapper.deleteByIds(ids));
    }

    @Override
    public boolean addRoleUsers(String roleId, String[] userIds) {
        return retBool(baseMapper.addRoleUsers(roleId, userIds));
    }

    @Override
    public boolean updateOrgCodes(String roleId, String[] orgCodes) {
        return retBool(baseMapper.updateOrgCodes(roleId, orgCodes));
    }
}
